<template>
  <!-- 
  {
    path: '/Detail/:rec_id',
    name: 'Detail',
    component: () => import('../views/Detail.vue'),
    props: true,
    meta: {
      tabbarshow: false,
    }
  },
 -->
  <div v-if="rec_info">
    <div class="box" @scroll="boxScroll($event)" ref="bigBox">
      <!-- header部分 -->
      <!-- 顶部头像区域 -->
      <van-nav-bar fixed :class="{ nav_on }">
        <template #left>
          <router-link to="/menu"
            ><van-icon name="arrow-left" size="18" color="#fff"
          /></router-link>
          <!-- 隐藏的顶部区域页面滚动至一定距离开始显示 -->
          <div class="hidden_user" v-show="nav_show">
            <img :src="user_info.avatar" alt="" class="head_img" />
            <p class="uname">{{ user_info.name }}</p>
            <van-button
              :icon="rec_info.isSub == 1 ? 'success' : 'plus'"
              size="small"
              type="danger"
              @click="updateSub"
              :title="rec_info.isSub == '0' ? '关注' : '取消关注'"
            >
              {{ rec_info.isSub == "0" ? "关注" : "已关注" }}</van-button
            >
          </div>
        </template>
        <template #right>
          <router-link to="/search">
            <van-icon name="search" size="18" class="r_search" color="#fff" />
          </router-link>
          <van-icon
            :name="nav_on ? 'back-top' : 'ellipsis'"
            size="18"
            class="r_more"
            color="#fff"
            @click="goToTop"
          />
          <!-- <van-icon name="" size="18" class="r_more" color="#fff"  v-show="nav_on"/> -->
        </template>
      </van-nav-bar>
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
        <swiper class="swiper" :options="swiperOption">
          <swiper-slide>
            <img
              :src="rec_info.mainImg[0].main_img"
              alt=""
              class="main_img"
              ref="main_img"
          /></swiper-slide>
          <div class="swiper-pagination" slot="pagination"></div>
        </swiper>
      </van-pull-refresh>
      <div class="content_area"></div>
      <van-cell-group ref="groupBox">
        <!-- 个人信息部分 -->
        <div class="user_info">
          <div class="head">
            <img :src="user_info.avatar" alt="" class="head_img" />
            <div class="cont_info" @scroll="head_box($event)">
              <p class="uname">{{ user_info.name }}</p>
              <p class="pub_time">{{ rec_info.pub_Time | timeFil }}</p>
            </div>
          </div>

          <div class="sub">
            <van-button
              :icon="rec_info.isSub == '1' ? 'success' : 'plus'"
              size="small"
              plain
              hairline
              type="danger"
              :title="rec_info.isSub == '0' ? '关注' : '取消关注'"
              @click="updateSub"
            >
              {{ rec_info.isSub == "0" ? "关注" : "已关注" }}</van-button
            >
          </div>
        </div>
        <van-cell class="content_title"
          ><h2>{{ rec_info.rec_name }}</h2></van-cell
        >
        <!-- 配料 -->
        <div class="ing_container">
          <p class="desc">{{ rec_info.desc }}</p>
          <div v-if="ingred[0].length">
            <van-cell class="ingredients"><h3>主料</h3></van-cell>
            <div v-for="i in ingred[0].length" :key="i">
              <van-cell
                :title="ingred[0][i - 1].i_name"
                is-link
                :value="ingred[0][i - 1].quant"
              />
            </div>
          </div>
          <div v-if="ingred[1].length">
            <van-cell class="ingredients"><h3>辅料</h3></van-cell>
            <div v-for="i in ingred[1].length" :key="i">
              <van-cell
                :title="ingred[1][i - 1].i_name"
                is-link
                :value="ingred[1][i - 1].quant"
              />
            </div>
          </div>
          <div v-if="ingred[2].length">
            <van-cell class="ingredients"><h3>调料</h3></van-cell>
            <div v-for="i in ingred[2].length" :key="i">
              <van-cell
                :title="ingred[2][i - 1].i_name"
                is-link
                :value="ingred[2][i - 1].quant"
              />
            </div>
          </div>
        </div>
        <!-- 步骤 -->
        <div class="steps" ref="stepBox">
          <div class="step_item" v-for="n in steps.length" :key="n">
            <div>
              <van-cell class="ingredients"
                ><h3>步骤{{ n }}</h3></van-cell
              >
              <van-cell class="step_img"
                ><img :src="steps[n - 1].imgs" alt=""
              /></van-cell>
              <van-cell class="step_text"
                ><p>
                  {{ steps[n - 1].desc }}
                </p></van-cell
              >
            </div>
          </div>
        </div>
        <!-- 评论 -->
        <div class="comments">
          <van-cell><h3 class="comment">发表评论</h3></van-cell>
          <div class="empty" v-if="comment.length == 0">
            <h4>暂无评论</h4>
            <p>快来抢沙发吧!</p>
          </div>
          <div class="com_container" v-else>
            <van-list
              v-model="loading2"
              :finished="finished2"
              finished-text="没有更多了"
              @load="onLoad"
              offset="1"
            >
              <div
                class="com_items"
                v-for="(item, index) in comment"
                :key="index"
              >
                <div class="user_info">
                  <div class="head">
                    <img :src="item.upic" alt="" class="head_img" />
                    <div class="cont_info">
                      <p class="uname_comment">
                        <span class="uname">
                          {{ item.uname }}
                        </span>
                        <!-- item.uid==rec_info.u_id过滤作者 -->
                        <span
                          class="author_tag"
                          v-show="item.uid == rec_info.u_id"
                          >作者</span
                        >
                      </p>
                      <p class="pub_time">
                        <span class="com_floor">{{ index + 1 }}#</span
                        >{{ item.time | timeFil }}
                      </p>
                    </div>
                  </div>
                  <div class="sub">
                    <span>{{ item.like_num | aweFil }}</span>
                    <van-icon
                      :name="
                        rec_info.likeState[index] == 0
                          ? 'good-job-o'
                          : 'good-job'
                      "
                      size="22px"
                      @click.self="dianZan($event, index)"
                    />
                  </div>
                </div>
                <div class="com_text_container">
                  <div class="com_text">
                    <p class="reply">
                      {{ item.txt }}
                    </p>
                    <!--  -->
                  </div>
                </div>
              </div>
            </van-list>
            <!-- <div class="com_items">
            <div class="user_info">
              <div class="head">
                <img :src="data.head" alt="" class="head_img" />
                <div class="cont_info">
                  <p class="uname_comment">
                    {{data.username}}<span class="author_tag">作者</span>
                  </p>
                  <p class="pub_time">
                    <span class="com_floor">2#</span>2021/12/8 14:49
                  </p>
                </div>
              </div>
              <div class="sub">
                <span>{{ aweArr[1] | aweFil }}</span
                ><van-icon
                  :name="dz_icons[1]"
                  size="22px"
                  @click="dianZan($event, 1)"
                />
              </div>
            </div>
            <div class="com_text_container">
              <div class="com_text">
                <p class="reply">
                  适度甜食护肝,吃甜食可以让人心情愉悦适度甜食护肝,吃甜食可以让人心情愉悦适度甜食护肝,吃甜食可以让人心情愉悦适度甜食护肝,吃甜食可以让人心情愉悦
                </p>
                <p class="be_replied">
                  JZLWWW:一看见就甜食就精神一看见就甜食就精神一看见就甜食就精神一看见就甜食就精神一看见就甜食就精神一看见就甜食就精神一看见就甜食就精神一看见就甜食就精神一看见就甜食就精神一看见就甜食就精神一看见就甜食就精神一看见就甜食就精神
                </p>
              </div>
            </div>
          </div> -->
          </div>
        </div>

        <!-- <div class="drag_fresh">上拉阅读下一篇</div>此功能待开发 -->
      </van-cell-group>

      <div class="detail_bottom" ref="bottom_change"></div>
      <!-- 评论输入框 -->
      <div class="comment_inp" v-show="comment_show" ref="comment_inp">
        <van-field
          v-model="comment_message"
          rows="2"
          :autosize="{ maxHeight: '73px' }"
          :label="`评论`"
          type="textarea"
          maxlength="50"
          placeholder="有爱评论,说点好听的"
          show-word-limit
        >
          <template #button>
            <van-button size="small" type="primary" @click="subComment"
              >提交</van-button
            >
          </template>
        </van-field>
      </div>
      <van-share-sheet
        v-model="showShare"
        title="立即分享给好友"
        :options="options"
        @select="onSelect"
      />
      <!-- 底部tabbar -->
      <van-tabbar fixed>
        <van-tabbar-item icon="chat-o" @click="goToComment"
          >评论({{ resLength }})</van-tabbar-item
        >
        <van-tabbar-item
          :icon="rec_info.collectState == '1' ? 'star' : 'star-o'"
          @click="addToCollect"
          >收藏({{ rec_info.clt_num }})</van-tabbar-item
        >
        <van-tabbar-item icon="description" @click="addToMenu"
          >加入菜单</van-tabbar-item
        >
        <van-tabbar-item icon="share-o" @click="showShare = true"
          >分享</van-tabbar-item
        >
      </van-tabbar>
      <!-- 置顶图标 -->
      <!-- <div class="backTopIcon" v-show="nav_on">
      <van-icon name="back-top" @click="goToTop"/>
    </div> -->
    </div>
  </div>
</template>

<script>
import moment from "moment";
import { Swiper, SwiperSlide } from "vue-awesome-swiper";
import { Toast } from "vant";
import "swiper/css/swiper.css";
export default {
  components: {
    Swiper,
    SwiperSlide,
  },
  data() {
    return {
      isLoading: true, //页面刷新加载状态
      loading2: false, //评论加载状态
      finished2: false, //评论加载完成
      // collect_on:false,
      nav_show: false,
      //顶部隐藏的navbar中的区域show属性
      nav_on: false,
      //顶部隐藏的navbar中的区域class属性
      comment_show: false, //评论展示状态
      comment_message: "", //评论内容
      offset: 0, //页面评论数据偏移量
      resLength: null, //评论数量
      commentTimer: null, //评论提交定时器
      uid: null, //用户id,测试模式下给1
      swiperOption: {
        loop: true, //轮播图循环
        autoHeight: true, //高度自适应
        pagination: {
          el: ".swiper-pagination",
          type: "fraction", //分页
        },
      }, //轮播图配置项
      showShare: false,
      user_info: {}, //当前菜品用户信息
      ingred: [], //食材信息
      steps: [], //步骤信息
      comment: [], //评论
      rec_info: null, //菜品表中菜品的所有信息
      options: [
        [
          { name: "微信", icon: "wechat" },
          { name: "朋友圈", icon: "wechat-moments" },
          { name: "微博", icon: "weibo" },
          { name: "QQ", icon: "qq" },
        ],
        [
          { name: "复制链接", icon: "link" },
          { name: "分享海报", icon: "poster" },
          { name: "二维码", icon: "qrcode" },
          { name: "小程序码", icon: "weapp-qrcode" },
        ],
      ], //分享面板配置项
    };
  },
  methods: {
    //回到顶部
    goToTop() {
      this.$refs.bigBox.scrollTop = 0;
    },
    // 滚动加载更多
    onLoad() {
      setTimeout(() => {
        this.offset += 5;
        //评论数偏移量,每次触发就增加五条数据至评论中
        let url = `/users/comment?u_id=${this.uid}&rec_id=${this.rec_id}&offset=${this.offset}`;
        this.$axios.get(url).then((res) => {
          let { result } = res.data;
          console.log(result);
          this.comment.push(...result.comment);
          this.rec_info.likeState.push(...result.likeState);
          this.loading2 = false;
          if (this.comment.length == this.rec_info.resLength) {
            this.finished2 = true;
            Toast("我是有底线的哟(*^▽^*)");
          }
          console.log(result.comment);
        });
      }, 600);
    },
    //下拉刷新页面数据
    onRefresh() {
      setTimeout(() => {
        this.getData();
        this.finished2 = false;
        this.offset = 0;
        Toast("刷新成功");
        this.isLoading = false;
      }, 1000);
    },
    // 提交评论
    subComment() {
      //还有待发送完成的请求
      // 处理频繁请求
      if (this.commentTimer) {
        Toast("评论过于频繁,一会儿再试吧(*^▽^*)");
        return;
      }
      //过滤空白内容的评论
      let txt = this.comment_message;
      if (!txt.trim()) {
        Toast("评论内容为空");
        return;
      }
      //发起请求
      this.commentTimer = setTimeout(() => {
        let time = moment().format("YYYY-MM-DD HH:mm:ss");
        let url = `/users/comment?u_id=${this.uid}&rec_id=${this.rec_info.id}&txt=${txt}&time=${time}`;
        this.$axios.get(url).then((res) => {
          console.log(res);
          if (res.data.code == 200) {
            this.comment.push(res.data.result);
            this.rec_info.likeState.push(0);
            this.rec_info.resLength += 1;
            this.$refs.bigBox.scrollTop = this.$refs.bigBox.scrollTop;
          } else {
            Toast(res.data.msg);
          }
        });
        window.scrollTop = this.$refs.bigBox.clientHeight;
        this.comment_message = "";
        this.commentTimer = null;
      }, 500);
    },
    //点击后页面自动定位到评论
    goToComment() {
      this.$refs.bigBox.scrollTop = this.$refs.bigBox.scrollHeight - 880;
    },
    //加入收藏
    addToCollect() {
      let url = `/users/collect?uid=${this.uid}&rec_id=${this.rec_info.id}`;
      this.$axios.get(url).then((res) => {
        let msg = res.data.msg;
        let formdata = `u_id=${this.uid}&rec_id=${this.rec_info.id}&rec_name=${
          this.rec_info.rec_name
        }&rec_dec=${"暂无详情"}&picurl=${this.rec_info.mainImg[0].main_img}`;
        this.$axios.post("/users/addcollect", formdata).then((res) => {
          console.log(res);
        });
        Toast(msg); //提示操作结果
      });
      if (this.rec_info.collectState == 1) {
        this.rec_info.clt_num -= 1;
        this.rec_info.collectState = 0;
        return;
      }
      this.rec_info.clt_num += 1;
      this.rec_info.collectState = 1;
    },
    //添加至菜单
    addToMenu() {
      Toast.success("添加成功");
    },
    //分享面板
    onSelect(option) {
      Toast(option.name);
      this.showShare = false;
    },
    //关注状态更新
    updateSub() {
      this.rec_info.isSub = this.rec_info.isSub == 1 ? 0 : 1;
      let url = `/users/sub?uid=${this.uid}&ru_id=${this.rec_info.u_id}`;
      this.$axios.get(url).then((res) => {
        if (res.data.code == 200) {
          console.log(res.data.msg);
        } else {
          console.log(res.data.msg);
        }
      });
    },
    //页面滚动事件监听方法
    boxScroll({ target }) {
      //页面滚动scrolltop大于等于主图高度后显示顶部隐藏的菜谱作者信息并固定在顶部
      if (target.scrollTop >= this.$refs.main_img.clientHeight) {
        this.nav_show = true;
        this.nav_on = true;
      } else {
        this.nav_show = false;
        this.nav_on = false;
      }
      //计算步骤中间的scrolltop值
      let step_scrolltop =
        this.$refs.main_img.clientHeight +
        this.$refs.groupBox.clientHeight -
        this.$refs.stepBox.clientHeight;
      // console.log(step_scrolltop);
      // console.log(target.scrollTop);
      // console.log(this.comment_show);
      //页面滚动scrolltop大于等于上面计算出的值之间时展示底部评论框,并固定在底部
      if (target.scrollTop >= step_scrolltop) {
        this.comment_show = true;
        this.$refs.bottom_change.style.marginBottom =
          this.$refs.comment_inp.clientHeight + "px";
      } else {
        this.comment_show = false;
      }
    },
    //点赞
    dianZan({ target }, index) {
      let url = `/users/like?cid=${this.comment[index].id}&uid=${this.uid}`;
      this.$axios.get(url).then((res) => {
        if (res.data.code == 200) {
          if (target.className == "van-icon van-icon-good-job-o") {
            target.className = "van-icon van-icon-good-job";
            target.style.color = "#ee0a24";
            this.comment[index].like_num += 1;
            console.log(this.comment[index].like_num);
          } else {
            target.className = "van-icon van-icon-good-job-o";
            target.style.color = "unset";
            this.comment[index].like_num -= 1;
            console.log(this.comment[index].like_num);
          }
        }
      });
      // if (target.className == "van-icon van-icon-good-job-o") {
      //   console.log(1111);
      //   target.className = "van-icon van-icon-good-job";
      //   target.style.color = "#ee0a24";
      //   this.com_data[index].awe += 1;
      //   console.log(this.com_data[index].awe);
      // } else {
      //   target.className = "van-icon van-icon-good-job-o";
      //   target.style.color = "unset";
      //   this.com_data[index].awe -= 1;
      //   console.log(this.com_data[index].awe);
      // }
    },
    //初始化数据方法
    getData() {
      this.uid = JSON.parse(localStorage.getItem("userinfo")).uid;
      let url = `/users/detail?u_id=${this.uid}&rec_id=${this.rec_id}`;
      this.$axios.get(url).then((res) => {
        let { result } = res.data;
        console.log(result);
        this.user_info = result.uinfo;
        this.ingred = result.ingred;
        this.steps = result.steps;
        this.comment = result.comment;
        this.rec_info = result;
        this.resLength = result.resLength;
        console.log(this.rec_info.mainImg[0].main_img);
      });
    },
  },
  //接收路由传参的菜品id
  props: ["rec_id"],
  mounted() {
    if (!localStorage.getItem("userinfo")) {
      Toast.fail({
        message: "请登录",
        onClose: () => {
          this.$router.push("/login");
        },
      });
      return;
    }
    //初始化数据
    this.getData();
    console.log(moment().format("YYYY-MM-DD HH:mm:ss"));
  },
  filters: {
    //点赞数过滤器
    aweFil(val) {
      let num_w = val / 1000;
      let num_k = val / 100;
      if (num_w >= 10) {
        return Math.floor(num_w) / 10 + "W";
      } else if (val / 100 >= 10) {
        return Math.floor(num_k) / 10 + "K";
      }
      return val;
    },
    //时间过滤器
    timeFil(val) {
      return moment(val).format("YYYY/MM/DD HH:mm:ss");
    },
  },
};
</script>

<style lang="scss" scoped>
.r_more {
  display: inline-block;
  margin-top: -3px;
}
.van-icon-good-job:before {
  color: #ee0a24;
}
.comment_inp {
  position: fixed;
  bottom: 50px;
  .van-field__label {
    width: 3.2em;
  }
  .van-cell {
    width: 100vw;
    height: 10vh;
    min-height: 88px;
  }
}
.van-nav-bar {
  z-index: 9;
}
.swiper-wrapper {
  color: white;
}
.swiper-pagination-fraction {
  color: white;
  background-color: rgba(50, 50, 50, 0.8);
  border-radius: 4px;
  width: 14vw;
  line-height: 14px;
  height: 14px;
  margin: 0 auto;
  left: 43vw;
  // top: 68vw;
}
.hidden_user {
  padding-left: 2vw;
  display: flex;
  align-items: center;
  .head_img {
    display: block;
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }
  .uname {
    margin-left: 1vw;
    width: 24vw;
    height: 24px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .van-button--small {
    height: 24px !important;
  }
  .van-button {
    margin-left: 1vw;
    border-radius: 7px;
    .van-icon {
      color: white !important;
    }
  }
}
.nav_on {
  background-color: white !important;
  .van-icon {
    color: #505050 !important;
  }
}
.box {
  height: 100vh;
  position: relative;
  overflow: scroll;
}
.r_search {
  margin-right: 20px;
}
.desc {
  padding: 10px 16px;
  font-size: 16px;
}
.content_title {
  padding: 6px 16px 0 16px;
  h2 {
    font-weight: bolder;
  }
}
.van-button--hairline::after {
  border-color: inherit;
  border-radius: 36px !important;
}
// .user_box{
//   overflow: scroll;
//   height: 100vh;
// }
.com_container {
  display: flex;
  flex-direction: column-reverse;
}
.com_text {
  margin-bottom: 16px;
  letter-spacing: 0.5px;
  .reply {
    margin-top: 0;
    width: 72vw;
    margin-left: 70px;
    margin-right: 10px;
    margin-bottom: 4px;
    line-height: 22px;
    font-size: 14px;
    white-space: wrap;
  }
  .be_replied {
    box-sizing: border-box;
    width: 72vw;
    margin-left: 70px;
    margin-right: 10px;
    margin-bottom: 4px;
    padding: 8px 8px;
    line-height: 22px;
    font-size: 13px;
    white-space: wrap;
    border-radius: 4px;
    background-color: rgb(213, 206, 206);
    color: #767575;
  }
}
.user_info {
  display: flex;
  padding: 0px 16px;
  align-items: center;
  justify-content: space-between;
  .head {
    display: flex;
    align-items: center;
  }
  .head_img {
    display: block;
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }
  .cont_info {
    margin-left: 10px;
    width: 55vw;
    .uname {
      font-weight: 800;
    }
    .uname_comment {
      display: inline-flex;
      font-size: 14px;
      margin-bottom: 4px;
      font-weight: 800;
      width: 100%;
      .uname {
        font-size: 16px;
        margin-bottom: 4px;
        max-width: 40vw;
        overflow: hidden;
        display: inline-block;
        height: 20px;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .author_tag {
        margin-left: 2vw;
        padding: 0 1px;
        display: inline-block;
        line-height: 17px;
        font-size: 12px;
        text-align: center;
        width: 33px;
        height: 18px;
        margin-top: 2px;
        color: #ee0a24;
        border: 1px solid #ee0a24;
        border-radius: 8px;
      }
    }
    .pub_time {
      font-size: 12px;
      color: #505050;
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      margin-top: 0;
      text-overflow: ellipsis;
      .com_floor {
        display: inline-block;
        margin-right: 2vw;
      }
    }
  }

  .sub {
    white-space: nowrap;
    transition: 0.3s ease-in-out;
    span {
      font-size: 15px !important;
      line-height: 22px;
    }
  }
  .van-button::before {
    background-color: unset;
    border-color: unset;
  }
  .van-button {
    background-color: white;
    color: #ee0a24;
  }
}
.van-cell-group {
  .ingredients {
    h3 {
      font-size: 14px;
      color: #505050;
      font-weight: bold;
    }
    margin-top: 0px;
    padding: 6px 16px 0 16px;
  }
  .step_img img {
    display: block;
    width: 100%;
  }
  .step_text {
    padding: 2px 16px;
  }
  .comments {
    .comment {
      font-weight: bolder;
      color: #000;
    }
    .empty {
      padding-top: 6vh;
      height: 14vh;
      h4 {
        color: #505050;
        width: 100%;
        text-align: center;
      }
      p {
        color: #999;
        width: 100%;
        text-align: center;
      }
    }
  }
  .drag_fresh {
    width: 100%;
    margin-bottom: 4vh;
    text-align: center;
    color: #999;
  }
}
.van-cell__value {
  text-align: unset;
}
.van-nav-bar {
  background-color: transparent;
}
.van-hairline--bottom::after {
  border-bottom-width: 0;
}
.van-button--hairline::after {
  border-radius: 12px !important;
}
.main_img {
  display: block;
  width: 100vw;
}
.detail_bottom {
  width: 100vw;
  height: 50px;
}
.van-tabbar-item--active {
  color: #646566;
}
</style>
